package com.medranocg.gd

import java.text.SimpleDateFormat
import java.sql.SQLException

import org.apache.commons.logging.LogFactory

import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional
import grails.converters.JSON

@Transactional(readOnly = true)
class DocumentTypeController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    static final log = LogFactory.getLog(this)
    def documentTypeService
    
    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        def offset = params.offset ? params.offset as Integer: 0
        def model = [documentTypeInstanceCount: DocumentType.count(), 
                     offset: offset, 
                     itemsPerPage: params.max]
        def documentTypes = DocumentType.list(max: params.max,
                                              offset: offset,
                                              sort: 'name')
        respond documentTypes, model: model
    }

    def show(DocumentType documentTypeInstance) {
        respond documentTypeInstance
    }

    def create() {
        respond new DocumentType(params)
    }

    @Transactional
    def save(DocumentType documentTypeInstance) {
        if (documentTypeInstance == null) {
            notFound()
            return
        }

        if (documentTypeInstance.hasErrors()) {
            respond documentTypeInstance.errors, view:'create'
            return
        }

        params.fileTypes.each {
            def fileType = FileType.get(it)
            documentTypeInstance.addToFileTypes(fileType)
        }

        documentTypeInstance.save flush:true

        request.withFormat {
            form {
                flash.message = message(code: 'documentType.created.message', args: [message(code: 'documentType.label', default: 'Tipo de documento'), documentTypeInstance.id])
                redirect documentTypeInstance
            }
            '*' { respond documentTypeInstance, [status: CREATED] }
        }
    }

    def edit(DocumentType documentTypeInstance) {
        respond documentTypeInstance
    }

    @Transactional
    def update(DocumentType documentTypeInstance) {
        if (documentTypeInstance == null) {
            notFound()
            return
        }

        if (documentTypeInstance.hasErrors()) {
            respond documentTypeInstance.errors, view:'edit'
            return
        }

        def currentFileTypes = documentTypeInstance.fileTypes.collect { it }
        params.fileTypes = params.fileTypes ?: []
    
        currentFileTypes.each {
            if (!params.fileTypes.contains(it.id.toString())) {
                documentTypeInstance.removeFromFileTypes(it)         
            }
        }

        params.fileTypes.each {
            def fileType = FileType.get(it)
            documentTypeInstance.addToFileTypes(fileType)
        }

        documentTypeInstance.save flush:true

        request.withFormat {
            form {
                flash.message = message(code: 'documentType.updated.message', args: [message(code: 'documentType.label', default: 'tipo de documento'), documentTypeInstance.id])
                redirect documentTypeInstance
            }
            '*'{ respond documentTypeInstance, [status: OK] }
        }
    }

    @Transactional
    def delete(DocumentType documentTypeInstance) {

        if (documentTypeInstance == null) {
            notFound()
            return
        }
        
        def deleted = documentTypeService.deleteDocumentType(documentTypeInstance.id)
        if (!deleted.success) {
            flash.success = false
            flash.message = message(
                code: deleted.messageCode, 
                args: [message(code: 'documentType.label', default: 'DocumentType')])
            redirect action: 'show', id: documentTypeInstance.id
            return 
        }

        request.withFormat {
            form {
                flash.success = true
                flash.message = message(
                    code: deleted.messageCode, 
                    args: [message(code: 'documentType.label', default: 'DocumentType'), documentTypeInstance.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'documentTypeInstance.label', default: 'DocumentType'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    def documentTypesJSON() {

        def documentTypes = DocumentType.list()
        def docTypesMap = [:]
        def now = new Date()
        def sdf = new SimpleDateFormat(params.get('dateFormat', 'yyyy-MM-dd')) 

        def docTypeToMap = { docType -> 

            def expirationDay = docType.defaultExpirationDay(now)
            
            [purgeable: docType.purgeable,
             hasExpiration: docType.hasExpiration,
             defaultExpirationDay: sdf.format(expirationDay)]       
        }

        documentTypes.each { docType -> 
            docTypesMap[docType.id.toString()] = docTypeToMap(docType)
        }
        
        render([documentTypes: docTypesMap] as JSON)

    }

}
